class Document < ActiveRecord::Base
  belongs_to :section
  has_many :decorate_documents, :dependent => :destroy
  has_many :decorates, :through => :decorate_documents

  def before_save
    self.body_html = Document.render_body_html self.body_textile
    if self.code.empty?
      self.code = self.subject
    end
    self.code = self.code.gsub(/\s+/m, "_")
  end

  def javascripts
    self.decorates.find :all, :conditions => { :decorate_type => "javascript" }
  end

  def stylesheets
    self.decorates.find :all, :conditions => { :decorate_type => "stylesheet" }
  end

  def self.render_body_html(textile_string)
    temp_textile = Document.render_code_tag textile_string
    rendered_body = RedCloth.new temp_textile
    rendered_html = rendered_body.to_html :textile
    rendered_html.gsub(/<a/,"<a target='_top' ")
  end

  def self.render_code_tag(text)
    result_html = text.gsub(/\{code.*?\}.*?\{\/code\}/m) { |target|
      data = target.scan(/\{code(.*?)\}(.*?)\{\/code\}/m)[0]
      code_type = nil
      unless data[0].empty?
        code_type = "html"
      end

      rendered_code = data[1].strip
      rendered_code = rendered_code.gsub(/</m, "&lt;") 
      rendered_code = rendered_code.gsub(/>/m, "&gt;") 
      rendered_code = rendered_code.gsub(/\n/m, "<br/>") 
      
      result = %Q{\r\n<notextile>\r\n}
      result << %Q{<div class="consilience_sample">\r\n}
      result << %Q{<div class="consilience_sample_code">\r\n}
      #result << %Q{<pre name="consilience_code" class="js:collapse">\r\n}
      result << rendered_code
      #result << %Q{\r\n</pre>\r\n}
      result << %Q{\r\n</div>\r\n}
      if code_type == "html"
        result << %Q{<div class="consilience_sample_preview">\r\n}
        result << data[1].strip
        result << %Q{</div>\r\n}
      end
      result << %Q{</div>\r\n}
      result << %Q{</notextile>\r\n}
      target = result
    }
  end
end
